package cn.ecnu.controller.files;

import cn.ecnu.common.utils.ImageUtil;
import cn.ecnu.common.utils.R;
import cn.hutool.core.io.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {

    private static final String rootPath = System.getProperty("user.dir") + "/files/profile/";

    @PostMapping("/profile/upload")
    public R upload(@RequestParam("userId")Integer userId, MultipartFile file) throws Exception {
        if (!ImageUtil.checkFileType(file)) {
            return R.error("图片格式不支持");
        }
        if (file.getSize()/1000000 > 10){
            return R.error("请上传大小为10MB以内的图片");  //可以在yml里面设置最大文件大小吧
        }
        file = ImageUtil.getCompressFile(rootPath, file);  //压缩图片，此任务工作在一个临时空间中
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));  //获取文件后缀名，带点号的如.jpg
        String flag = userId.toString();   //这里我就直接用userId作flag了，通常的flag应该是UUID
        String filePath = rootPath + flag + suffix;
        FileUtil.writeBytes(file.getBytes(), filePath); //写文件
        return R.ok();
    }

    @GetMapping("/profile/{flag}") /*flag is userId*/  //没用数据库，性能待优化
    public void getFile(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(rootPath);
        String fileName = fileNames.stream().filter(name -> name.startsWith(flag+".")).findAny().orElse("default.jpg");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            byte[] bytes = FileUtil.readBytes(rootPath + fileName);  // 通过文件的路径读取文件字节流
            os = response.getOutputStream();   // 通过输出流返回文件
            os.write(bytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
